/*
 * @Author: lin_zizhuo 2297304135@qq.com
 * @Date: 2023-12-05 18:13:36
 * @LastEditors: lin_zizhuo 2297304135@qq.com
 * @LastEditTime: 2023-12-07 08:21:22
 * @FilePath: /thread_text/mytheard.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <string>
#include <memory>
#include <unistd.h>
// 线程库属于第三方库，所以编译的时候需要进行手动链接
#include <pthread.h>

using namespace std;
// 从实验可以发现，全局数据区内的数据是线程共享的
int g_val = 100;

class sumRequest
{
public:
    int _start;
    int _end;
    string _threadName;

public:
    sumRequest(const int start, const int end, const string &threadName)
        : _start(start), _end(end), _threadName(threadName) {}
    int run()
    {
        int sum = 0;
        for(int i = _start; i <= _end; ++i)
            sum += i;
        return sum;
    }
};

class sumResult
{
public:
    int _sum;
    string _thread;
};

void *childRun(void *args)
{
    unique_ptr<sumRequest> re(static_cast<sumRequest*>(args));
    // cout << re->_start << ' ' << re->_end << endl;
    int sum = re->run();
    // cout << sum << endl;
    sumResult* ret = new sumResult;
    ret->_sum = sum;
    ret->_thread = re->_threadName;
    // 线程结束的方法一：通过return返回
    // return (void*)1;
    // 结束方法二：pthread_exit
    // cout << ret->_sum << endl;
    return static_cast<void*>(ret);
}

int main()
{
    pthread_t tid;
    // tid是线程id，但与操作中定位线程的id是不一样的，和共享内存一样
    // 操作系统中以LWP作为线程的唯一标识符
    sumRequest* args = new sumRequest(0, 100, "thread-1");
    int n = pthread_create(&tid, nullptr, childRun, static_cast<void*>(args));
    if (n)
    {
        perror("pthread_create");
        exit(1);
    }
    sleep(1); // 为了保证新线程已经启动

    // 线程结束方法三: 直接在主线程进行cancel操作
    // pthread_cancel(tid);
    // while (true)
    // {
    //     printf("I' m main thread, my pid is: %d , g_val:%d\n", getpid(), g_val++);
    //     sleep(1);
    // }
    // void* ret, *text;
    // pthread_join(tid, &text);
    
    void* ret;
    pthread_join(tid, &ret);
    sumResult* result = static_cast<sumResult*>(ret);
    cout << result->_sum << endl;
    delete result;

    // cout << n << endl;
    // cout << "thread quit, ret: " << (long long int)ret << endl;
    
    return 0;
}